<template>
  <div>
    <el-dialog
      modal-class="cailiaozuhe-dialog"
      v-model="_isOpen"
      width="1200"
      :title="'根据条件组合添加'"
      align-center
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <template #header>
        <h4>根据条件组合添加</h4>
      </template>
      <template #default>
        <header>
          <div class="left">
            <h3 v-if="props.optionInfo.type === 'zhu'">主材数量：{{ _detail.limitProductNum || "-" }}</h3>
            <h3 v-if="props.optionInfo.type === 'fu'">辅材数量：{{ _detail.limitProductNum || "-" }}</h3>
            <h3 class="ml50">限制金额：¥{{ _detail.limitProductMoney || "-" }}</h3>
          </div>
        </header>

        <div class="list-wrap">
          <template v-if="tableData.length > 0">
            <div class="list-item" v-for="(item, index) in tableData" :key="index">
              <p class="mb16">
                {{ item.categoryNameList.join("-") }}
                <span>（成本：{{ item.costTotalPriceMin }}~{{ item.costTotalPriceMax }}）</span>
              </p>
              <div class="block">
                <div class="block-item" v-for="(item2, index2) in item.productProList" :key="index2">
                  {{ item2.stastsName || "-" }}
                </div>
              </div>
            </div>
          </template>
          <el-empty v-else description="这里暂时什么都没有" />
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <div style="flex: auto">
            <el-button type="info" @click="cancelClick">取消</el-button>
            <el-button type="primary" v-if="optionInfo.actionType === 'edit'" @click="confirmClick">保存</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { Search } from "@element-plus/icons-vue";
import { updateQuoteProductNum, saveAddition, deleteAddition } from "@/apis/quote-price/following";
import useCodeArrStore from "@/store/modules/select";

const emit = defineEmits(["update:isOpen", "submitOk"]);
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  optionInfo: {
    type: Object,
    default: () => {
      return {
        actionType: "edit", //edit view
        type: "zhu", //zhu-主材 fu-辅材
        project: {}, //项目obj
        detail: {}, //明细详情
        getDetailList: null //查询主材、辅材明细列表
      };
    }
  }
});
const conditionRef = ref();
const form = ref({});
const formRef = ref();
const tableData = ref([]);
const conditionIsOpen = ref(false); //条件内、条件外选商品sku
const optionInfoCondition = ref({ budgetId: "", contentId: "", productType: -1, detail: {} });
const _detail = ref({});
const _project = ref({});

watch(
  () => props.isOpen,
  val => {
    if (val) {
      //生成临时code-时间戳
      localStorage.setItem("followingObj", JSON.stringify({ _time: new Date().getTime() }));
      console.log("//生成临时code-时间戳==================");
    }
  },
  { deep: true, immediate: false }
);

watch(
  () => props.optionInfo.detail._time,
  val => {
    console.log("条件组合-传递过来的主材辅材明细", props.optionInfo);

    _detail.value = props.optionInfo.detail;
    _project.value = props.optionInfo.project;

    tableData.value = props.optionInfo.detail.voList || [];
    tableData.value.map(item => {
      const NUM = item.productNum;
      item._productNum = NUM; //原有的数量数据，手动更改数量后，不会对它造成影响
    });
    form.value = {
      limitProductNum: _detail.value.limitProductNum,
      limitProductMoney: _detail.value.limitProductMoney
    };
  },
  { deep: true, immediate: false }
);

//删除明细里面的增项
const delContOut = item => {
  deleteAddition({ ...item }).then(async res => {
    if (res.code === 200) {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      //再次查询明细接口
      await props.optionInfo.getDetailList(
        props.optionInfo.project,
        props.optionInfo.type === "zhu" ? 1 : 2,
        JSON.parse(localStorage.getItem("followingObj"))._time
      );
      changeNUM();
    }
  });
};

//添加材料后，再次查询接口
const conditionSubmit = () => {
  props.optionInfo.getDetailList(
    props.optionInfo.project,
    props.optionInfo.type === "zhu" ? 1 : 2,
    JSON.parse(localStorage.getItem("followingObj"))._time
  );
  conditionRef.value.clickClose(); //关闭商品选择sku弹窗
};

/**
 * 更改数量之后，前端计算报价（只做展示使用）
 * 如果是条件组合添加的，还要算出 是否超过了限制数量和限制金额
 */
const isExceedsLimit = ref(false); //是否超出了金额、数量限制
const changeNUM = () => {
  console.log("更改了数量", tableData.value);
  if (_project.value.mainProductShowType === 2 || _project.value.auxiliaryProductShowType === 2) {
    // 条件组合

    // 总报价-只计算增项的 isContOut === 1
    let price = 0;
    let limitPrice = 0; //更改数量后的限制金额（非增项的数量*报价）
    let limitNum = 0; //更改数量后的限制数量（增项的数量之和）
    tableData.value.map(item => {
      if (item.isContOut === 1) {
        // 增项
        price += Number(item.productNum) * Number(item.quoteUnitPrice);
      } else {
        //非增项
        limitPrice += Number(item.productNum) * Number(item.quoteUnitPrice);
        limitNum += Number(item.productNum);
      }
    });
    if (limitPrice > _detail.value.limitProductMoney || limitNum > _detail.value.limitProductNum) {
      isExceedsLimit.value = true; //是否超出了金额、数量限制
    } else {
      isExceedsLimit.value = false; //是否超出了金额、数量限制
    }
    _detail.value.quoteMoney = price;
  } else {
    // 商品添加
    let price = 0;
    tableData.value.map(item => {
      price += Number(item.productNum) * Number(item.quoteUnitPrice);
    });
    _detail.value.quoteMoney = price;
  }
};

const _isOpen = computed({
  get() {
    return props.isOpen;
  },
  set(value) {
    emit("update:isOpen", value);
  }
});

const cancelClick = () => {
  _isOpen.value = false;
  // emit("changeAttr");
};
const confirmClick = () => {
  if (_project.value.mainProductShowType === 2 || _project.value.auxiliaryProductShowType === 2) {
    // 根据条件组合添加
    if (isExceedsLimit.value) {
      return ElMessage({
        message: "超出了限制数量或者限制金额，请重新更改数量!",
        type: "error"
      });
    }
    tableData.value.map(item => {
      delete item._productNum;
      item.productNum = Number(item.productNum);
    });
    saveAddition({
      // contentId: _detail.value.contentId,
      productInfos: tableData.value
    }).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: "保存成功",
          type: "success"
        });
        _isOpen.value = false;
        emit("submitOk");
      }
    });
  } else {
    tableData.value.map(item => {
      delete item._productNum;
      item.productNum = Number(item.productNum);
    });
    // 根据商品添加
    updateQuoteProductNum({
      contentId: _detail.value.contentId,
      productInfos: tableData.value
    }).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: "保存成功",
          type: "success"
        });
        _isOpen.value = false;
        emit("submitOk");
      }
    });
  }
};

defineExpose({});
</script>

<style lang="scss">
.cailiaozuhe-dialog {
  .el-dialog {
    padding-left: 0 !important;
    padding-right: 0 !important;
    padding-bottom: 0 !important;
    .el-dialog__header {
      border-bottom: 1px solid #e2e8f0;
      padding: 0 24px 20px 24px;
    }
    .el-dialog__body {
      padding: 20px;
      header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        h3 {
          font-size: 16px;
          font-weight: normal;
          color: #3d3d3d;
          span {
            color: #ff3333;
          }
        }
        .left {
          display: flex;
          align-items: center;
          .el-form-item {
            margin-bottom: 0;
          }
        }
      }
      .list-wrap {
        .list-item {
          padding: 15px;
          background-color: #f3f5f7;
          margin-bottom: 20px;
          border-radius: 4px;
          & > p {
            color: #3d3d3d;
            span {
              color: #86909c;
            }
          }
          .block {
            display: flex;

            .block-item {
              border-radius: 20px;
              background-color: white;
              margin-right: 10px;
              padding: 4px 16px;
            }
          }
        }
      }
    }
    .el-dialog__footer {
      padding-top: 0;
    }
  }
  .dialog-footer {
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    margin: 0;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
<style lang="scss" scoped>
.el-button--primary {
  --el-button-bg-color: #424e66;
  border: none;
}
.el-button.el-button--info {
  --el-color-info: #f2f3f5;
  --el-color-white: #1d2129;
  &:hover {
    --el-button-hover-bg-color: #f2f3f5 !important;
    border-color: #f2f3f5 !important;
  }
}
</style>
